package org.kojo.tdrm.service.notic;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.apache.tools.ant.util.DateUtils;
import org.kojo.tdrm.entity.Task;
import org.kojo.tdrm.utils.App;

public class EmailNotification implements INotification {
	private static final Logger log = Logger.getLogger(EmailNotification.class.getName());
	
	public static String EMAIL = "EMAIL";
	public static String REM_TASKS = "REM_TASKS";
	private Map params = new HashMap(0);
	
	public EmailNotification(){
	
	}
	
	@Override
	public int publish() {
		Properties props = new Properties();
		Session session = Session.getDefaultInstance(props, null);
			String msgbody = "";
			String email = (String) params.get(EMAIL);
			try {
				Set<Task> remTasks=(Set<Task>)params.get(REM_TASKS);
				Message msg = new MimeMessage(session);
				msg.setFrom(new InternetAddress(App.ADMIN_EMAIL, "TDRM Admin"));
				msg.addRecipient(Message.RecipientType.TO, new InternetAddress(
						email, "TODO User"));
				msg.setSubject("Reminder for "+remTasks.size()+" tasks.");
				for(Task t:remTasks){
					msgbody +="Task:"+t.getName()+" Due Date:"+DateUtils.format(t.getDueDate(), DateUtils.ISO8601_DATETIME_PATTERN)+" \n";
				}
				msg.setText(msgbody);
				Transport.send(msg);
				log.fine("Send mail to ->"+email);
			} catch (AddressException ex) {
				log.log(Level.SEVERE, "Cannot Send email to "+email, ex);
			} catch (MessagingException ex) {
				log.log(Level.SEVERE, "Cannot Send email to "+email, ex);
			} catch (UnsupportedEncodingException ex) {
				log.log(Level.SEVERE, "Cannot Send email to "+email, ex);
			} 
		
		return 0;
	}

	@Override
	public void setParams(Map params) {
		this.params = params;
		
	}

}
